package com.cxb.receiver;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.media.AudioManager;
import android.os.Handler;
import android.util.Log;

public class WenWenStateReceiver extends BroadcastReceiver {

	// FmtransmitterManager fmtransmitterManager;
	private AudioManager audioManager;
	private Handler mHandler;
	private Runnable audioRecoverTask = new Runnable() {

		@Override
		public void run() {
			if (audioManager != null) {
				audioManager.setStreamMute(AudioManager.STREAM_MUSIC
						| AudioManager.STREAM_SYSTEM, false);
				print2Sd("mute false");
			}
		}
	};

	@Override
	public void onReceive(Context context, Intent intent) {
		int state = intent.getIntExtra("state", -1);
		if (mHandler == null) {
			mHandler = new Handler();
		}
		print2Sd("wenwen state= " + state);
		if (state >= 0) {
			if (audioManager == null) {
				audioManager = (AudioManager) context
						.getSystemService(Context.AUDIO_SERVICE);
			}
			audioManager.setStreamMute(AudioManager.STREAM_MUSIC
					| AudioManager.STREAM_SYSTEM, state == 1);
			print2Sd("mute " + (state == 1));
			if (state == 0) {
				mHandler.postDelayed(audioRecoverTask, 10000);
			} else if (state == 1) {
				mHandler.removeCallbacks(audioRecoverTask);
				Intent iRecorder = new Intent();
				iRecorder.setAction("preview_window_off");
				context.sendBroadcast(iRecorder);
			}
		}
		// if (fmtransmitterManager == null) {
		// fmtransmitterManager = new FmtransmitterManager(context);
		// }
		// int state = intent.getIntExtra("state", -1);
		// Debug.printf("test", "WenWenStateReceiver state=" + state);
		// if (state >= 0) {
		//
		// if (state == 0) {
		// if(fmtransmitterManager.getFMEnable(context)){
		// fmtransmitterManager.setSoundEnable(0);
		// }else{
		// fmtransmitterManager.setSoundEnable(1);
		// }
		// }else{
		// fmtransmitterManager.setSoundEnable(0);
		//
		// }
		//
		// }
	}

	private void print2Sd(String log) {
//		File file = new File("/mnt/sdcard/wenwenstate.log");
//
//		try {
//
//			if (!file.exists()) {
//				file.createNewFile();
//			}
//
//			FileOutputStream fos = new FileOutputStream(file, true);
//
//			// bufferedWriter.write(log+"\n");
//			fos.write((log + "\n").getBytes());
//
//			fos.flush();
//			fos.close();
//		} catch (Exception e) {
//
//			e.printStackTrace();
//		}

	}
}
